import os, io, subprocess
from PySide6.QtCore import QObject, Signal

class Png_Export(QObject):
    log_signal = Signal(str)  # 新增的信号，用于传递日志信息
    def __init__(self, img, input_file, output_file, interface):
        super().__init__()
        self.img = img
        self.input_file = input_file
        self.output_file = output_file
        self.interface = interface
        self.log_signal.connect(self.interface.log_signal)  # 连接日志信号到主界面日志更新槽

    def quant_oxipng(self):
        # 将图像保存到字节数组中
        img_byte_array = io.BytesIO()
        self.img.save(img_byte_array, format='PNG')
        img_byte_array.seek(0)

        # 处理文件名中的空格
        if " " in self.output_file:
            output_file = f'"{self.output_file}"'
        else:
            output_file = self.output_file
        quant_oxipng = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pngquant.exe')
        cmd = f"{quant_oxipng} --force --verbose --speed=1 --ordered 256 - --output {output_file}"
        proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
        stdout, stderr = proc.communicate(input=img_byte_array.read())
        if proc.returncode != 0:
            try:
                # 假设外部程序输出使用GBK编码
                error_message = stderr.decode('GBK')
            except UnicodeDecodeError as e:
                # 如果解码失败，尝试忽略解码错误
                error_message = stderr.decode('GBK', errors='ignore')

            self.log_signal.emit(f"压缩 {self.input_file} 出错：返回码 {proc.returncode}, 错误信息：{error_message}")

        elif proc.returncode == 99:
            self.log_signal.emit(f"{self.input_file} 未处理。")

        else:
            self.log_signal.emit(f"{self.input_file} 压缩成功。")